//
//  StatusService.m
//  CC
//
//  Created by Calvin.wang on 3/25/15.
//  Copyright (c) 2015 Calvin. All rights reserved.
//

#import "StatusService.h"
#import "SQLiteHelper.h"
#import "UserService.h"
#import "Status.h"

@interface StatusService()
@property SQLiteHelper *sqliteHelper;
@property UserService  *userService;
@end

@implementation StatusService
- (instancetype)init
{
    self = [super init];
    if (self) {
        _sqliteHelper=[[SQLiteHelper alloc] init];
        _userService=[[UserService alloc] init];
    }
    return self;
}

-(void) addStatus:(Status *)status{
    NSString *sql=[NSString stringWithFormat:@"INSERT INTO Status (source,createdAt,\"text\" ,user) VALUES('%@','%@','%@','%@')",status.source,status.createAt,status.text,status.user.Id];
    [_sqliteHelper executeNonQuery:sql];
}

-(void) removeStatus:(id)status{
    NSString *sql=[NSString stringWithFormat:@"DELETE FROM Status WHERE Id='%@'",status];
    [_sqliteHelper executeNonQuery:sql];
}

-(void) modifyStatus:(Status *)status{
     NSString *sql=[NSString stringWithFormat:@"UPDATE Status SET source='%@',createdAt='%@',\"text\"='%@' ,user='%@' WHERE Id='%@'",status.source,status.createAt,status.text,status.user.Id,status.Id];
    [_sqliteHelper executeNonQuery:sql];
}

-(Status *)getStatusById:(int)Id{
    Status *status=[[Status alloc]init];
    NSString *sql=[NSString stringWithFormat:@"SELECT Id, source,createdAt,\"text\" ,user FROM Status WHERE Id='%i'", Id];
    NSArray *rows= [_sqliteHelper executeQuery:sql];
    if (rows&&rows.count>0) {
        [status setValuesForKeysWithDictionary:rows[0]];
        status.user=[_userService getUserById:[(NSNumber *)rows[0][@"user"] intValue]] ;
    }
    return status;
}

-(NSArray *)getAllStatus{
    NSMutableArray *array=[NSMutableArray array];
    NSString *sql=@"SELECT Id, source,createdAt,\"text\" ,user FROM Status ORDER BY Id";
    NSArray *rows= [_sqliteHelper executeQuery:sql];
    for (NSDictionary *dic in rows) {
        Status *status=[self getStatusById:[(NSNumber *)dic[@"Id"] intValue]];
        [array addObject:status];
    }
    return array;
}
@end
